'use client'

import { useState, useRef } from 'react'
import Image from 'next/image'
import { CSSTransition } from 'react-transition-group'

import triangleGrayIcon from '@/public/triangle_gray_small.png'

interface DropDownProps {
  selectedId: string
  onSelect: (id: string) => void
  children: React.ReactNode
  items: Manufacturer[] | Model[]
}

const DropDownPC: React.FC<DropDownProps> = (props) => {
  const { selectedId, onSelect, children, items } = props
  const selectedItem = items.find(
    (item) => item.id.toString() === selectedId.toString()
  )
  const dropDownRef = useRef(null)
  const [isHover, setIsHover] = useState(false)

  return (
    <div
      className='relative'
      onMouseEnter={() => setIsHover(true)}
      onMouseLeave={() => setIsHover(false)}
    >
      <div
        className={`flex justify-between items-center rounded-[0.4375rem] text-[0.75rem] leading-[0.75rem] font-medium px-[0.8125rem] py-[0.875rem] border-[1px] border-solid border-[#E2E2E2] min-w-[9.6rem] 2xl:min-w-[12rem] 2xl:rounded-[0.65625rem] 2xl:text-[1.125rem] 2xl:leading-[1.125rem] 2xl:px-[1.21875rem] 2xl:py-[1.3125rem] cursor-pointer ${
          isHover ? '' : 'text-[#999999]'
        }`}
      >
        {selectedItem ? selectedItem.title : children}
        <div className='w-[0.1875rem]'></div>
        <div className='relative mt-1 w-[0.375rem] h-[0.34375rem]'>
          <Image
            src={triangleGrayIcon}
            alt='dropdown icon'
            fill
            sizes='(max-width: 1024px) 2vw'
          />
        </div>
      </div>
      {/* Hover 下拉 */}
      <CSSTransition
        nodeRef={dropDownRef}
        in={isHover}
        timeout={200}
        classNames='nav-item-dropdown'
        unmountOnExit
      >
        <div
          ref={dropDownRef}
          className='z-50 absolute top-[2.5rem] left-0 right-0 bg-white border-[1px] border-solid border-[#E2E2E2] rounded-[0.4375rem] 2xl:top-[3.75rem] 2xl:rounded-[0.65625rem]'
        >
          {items.map((item) => {
            return (
              <div
                key={item.id}
                className='flex justify-between items-center px-[0.8125rem] py-[0.875rem] 2xl:px-[1.21875rem] 2xl:py-[1.3125rem] text-[0.75rem] leading-[0.75rem] text-[#999999] 2xl:text-[1.125rem] 2xl:leading-[1.125rem] hover:text-[#333333] hover:bg-gray-100 cursor-pointer'
                onClick={() => {
                  setIsHover(false)
                  onSelect(item.id.toString())
                }}
              >
                {item.title}
              </div>
            )
          })}
        </div>
      </CSSTransition>
    </div>
  )
}

export default DropDownPC
